package com.jadows.tdog.repository;

import com.jadows.tdog.domain.Contact;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ContactRepository extends MongoRepository<Contact, String> {

    /**
     * 根据 unionId 查询联系人
     *
     * @param unionId unionId
     * @return 联系人
     */
    Contact findContactByUnionId(String unionId);

    /**
     * 根据 memberId 查询联系人
     *
     * @param mongoTemplate mongoTemplate
     * @param memberId      memberId
     * @return 联系人列表
     */
    default List<Contact> findContactsByMemberId(MongoTemplate mongoTemplate, String memberId) {
        Query query = new Query();
        Criteria criteria = new Criteria().orOperator(
                Criteria.where("fromUser.uid").is(memberId),
                Criteria.where("toUser.uid").is(memberId)
        );
        query.addCriteria(criteria);
        return mongoTemplate.find(query, Contact.class);
    }

    /**
     * 查询当前用户的屏蔽联系人
     */
    default List<Contact> findBlockContactsByMemberId(MongoTemplate mongoTemplate, String memberId) {
        Query query = new Query();
        Criteria criteria = new Criteria().orOperator(
                Criteria.where("toUser.uid").is(memberId).and("toUser.blocked").is(true),
                Criteria.where("fromUser.uid").is(memberId).and("fromUser.blocked").is(true)
        );
        query.addCriteria(criteria);
        return mongoTemplate.find(query, Contact.class);
    }

    /**
     * 根据 memberId 删除联系人
     */
    default List<Contact> removeContactByMemberId(MongoTemplate mongoTemplate, String memberId) {
        Query query = new Query();
        Criteria criteria = new Criteria().orOperator(
                Criteria.where("fromUser.uid").is(memberId),
                Criteria.where("toUser.uid").is(memberId)
        );
        query.addCriteria(criteria);
        // 待删除的联系人
        List<Contact> contacts = mongoTemplate.find(query, Contact.class);
        for (Contact contact : contacts) {
            Contact.ContactInfo contactInfo = contact.getContactInfoByUid(memberId);
            if (contactInfo == null) {
                continue;
            }
            contactInfo.setStatus(2);
        }
        // 批量更新
        saveAll(contacts);
        return contacts;
    }
}
